package com.ddstation.crm.organization_structure.controller;

import com.ddstation.crm.institution.entity.DtHealthManageInstitutionDoctorEntity;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.crm.organization_structure.entity.DtInvsOrganizationStructureStaffEntity;
import com.ddstation.crm.organization_structure.service.DataImportService;
import com.ddstation.crm.organization_structure.service.StaffService;
import com.ddstation.crm.organization_structure.util.ExcelUtil;
import com.ddstation.security.util.WnBizMsgCrypt;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 系统设置 （数据导入）
 */
@Controller @Lazy
public class DataImportController {

	@RequestMapping(value="config_data_import.do")
	public String configDataImport(
			Model model,
			HttpSession session) {

		// 从session获取基础数据
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
			return "forward:login?timeout=true"; // session 过期
		}

		String doctorUUID = WnBizMsgCrypt.encrypt(loginData.getDoctor().getSupervisorId().toString());
		model.addAttribute("doctorUUID", doctorUUID);
		return "pc/dataImport/dataImport";
	}


	@RequestMapping(value="config_data_import.do/downloadTemplate", method=RequestMethod.GET)
	public @ResponseBody void downloadTemplate(
			@RequestParam("templateType")String templateType,
			HttpServletResponse response, HttpServletRequest request) {
		//下载模板
		int i = dataImportService.downloadTemplate(response, request, templateType);
		if(i == 0){
			throw new RuntimeException("类型模板不存在");
		}else if(i == -1){
			throw new RuntimeException("下载模板失败");
		}
	}

	@RequestMapping(value="config_data_import.do/importExcel", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> importExcel(
			@RequestParam("templateType")String templateType,
			@RequestParam("importExcelFile") MultipartFile file,
			HttpSession session) {
		SessionLoginData loginData = (SessionLoginData) session.getAttribute(SessionLoginData.KEY);
		return dataImportService.importExcel(templateType, file, loginData.getInstitution().getId());
	}

	@Inject DataImportService dataImportService;
}
